/**
 * Copyright (C) 2009 IcyRiver / Wesley He
 *
 * IcyRiver Lib may be copied only under the terms of the GNU General
 * Public License V1, which may be found in the IcyRiver.net source kit.
 * Please visit the IcyRiver Home Page http://icyriver.net/ for more detail.
 **/

//socket_server.c

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#include <time.h>
#include <stdlib.h>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/time.h>

#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <netdb.h>

#include "socket.h"
#include "socket_server.h"


int g_server_port = SOCKET_SERVER_DEFAULT_PORT;
int g_max_connections = SOCKET_SERVER_DEFAULT_MAX_CONNECTONS;
int g_network_timeout = SOCKET_SERVER_DEFAULT_NETWORK_TIMEOUT;
int g_max_threads = 5;

int main(int argc, char *argv[])
{
	char bind_addr[SOCKET_SERVER_IP_ADDRESS_SIZE];
	int result;
	int server_sock;
	int client_sock;
	int recv_bytes;
	char recv_buf[SOCKET_SERVER_HEADER_SIZE];
	
	memset(bind_addr, 0, sizeof(bind_addr));

	//server_sock = g_socket_socket_server(bind_addr, g_server_port, &result);
	server_sock = g_socket_socket_server(NULL, g_server_port, &result);

	if (server_sock < 0)
	{
		return 0;
	}

	client_sock = g_socket_accept_select(server_sock, 1 * 60, &result);
	if(client_sock < 0) //error
	{
		if (result == ETIMEDOUT || result == EINTR || \
				result == EAGAIN)
		{
			return 0;
		}

		if(result == EBADF)
		{
			return 0;
		}

		return 0;
	}

	fprintf(stderr,"file: %s, line: %d: Successful! Connection to client is accepted.\n", \
			__FILE__, __LINE__);

	result = g_socket_tcp_recv_data_select(client_sock, recv_buf, \
			SOCKET_SERVER_HEADER_SIZE, g_network_timeout, &recv_bytes);
	if ( result == ETIMEDOUT )//timeout
	{
		return 0;
	}

	if (result != 0)
	{
		if (result == ENOTCONN && recv_bytes == 0)
		{
			return 0;
		}
		else
		{
			return 0;
		}
		return 0;
	}


#ifdef __DEBUG__
	fprintf(stderr,"file: %s, line: %d: got the messages: %s\n", \
			__FILE__, __LINE__, recv_buf);
#endif

	fprintf(stderr,"file: %s, line: %d: Disconnecting to client ....\n", \
			__FILE__, __LINE__);

	close(client_sock);

	fprintf(stderr,"file: %s, line: %d: Successful! Disconnected to client\n", \
			__FILE__, __LINE__);

	return 0;

}
